<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="机构名称" prop="name">
        <el-select
          v-model="queryParams.orgId"
          placeholder="请选择机构"
          clearable
          style="width: 160px"
        >
          <el-option
            v-for="item in orgTree"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="科室名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入科室名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          style="width: 160px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['system:dept:query']" @click="handleQuery"
          ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
        >
        <el-button v-hasPermi="['system:dept:query']" @click="resetQuery"
          ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
        >
        <el-button
          v-hasPermi="['system:dept:create']"
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button plain type="danger" @click="toggleExpandAll">
          <Icon class="mr-5px" icon="ep:sort" />
          展开/折叠
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap :body-style="{ height: 'calc(100vh - 200px)' }">
    <el-table
      class="tables"
      v-loading="loading"
      :data="list"
      row-key="id"
      :default-expand-all="isExpandAll"
      style="height: calc(100vh - 260px)"
      v-if="refreshTable"
    >
      <el-table-column prop="orgName" label="机构名称" />
      <el-table-column prop="name" :label="t('page_sys.dept.labelBmmc')" />
      <el-table-column prop="sort" label="排序" />
      <el-table-column prop="code" label="编码" />
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="使用范围" prop="scope">
        <template #default="scope">
          <div>{{ convertToChinese(JSON.parse(scope.row.scope)) }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column :label="t('table.action')" align="center">
        <template #default="scope">
          <el-button
            v-hasPermi="['system:dept:update']"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            <Icon icon="ep:edit" class="mr-5px" />
            编辑
          </el-button>
          <el-button
            v-hasPermi="['system:dept:create']"
            link
            type="primary"
            @click="openForm('create', scope.row.id)"
          >
            <Icon icon="ep:plus" class="mr-5px" />
            新增
          </el-button>
          <el-button
            v-hasPermi="['system:dept:delete']"
            link
            type="danger"
            @click.stop="handleDelete(scope.row.id)"
          >
            <Icon icon="ep:delete" class="mr-5px" />
            {{ t('action.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
  <!-- <div class="w-3/5 ml-15px">
      <ContentWrap
        :title="t('page_sys.dept.titleBmxx')"
        :showFooter="true"
        :body-style="{ height: 'calc(100vh - 328px)' }"
      >
        <el-form
          class="-mb-15px"
          v-loading="formLoading"
          :model="formData"
          ref="editFormRef"
          :rules="formRules"
          label-width="auto"
          label-position="right"
        >
          <el-form-item :label="t('page_sys.dept.labelBmmc')" prop="name">
            <el-input
              v-model="formData.name"
              :placeholder="t('page_sys.dept.placeholderBmmc')"
              style="width: 260px"
            />
          </el-form-item>
          <el-form-item :label="t('page_sys.dept.labelSjbm')" prop="parentId">
            <el-tree-select
              v-model="formData.parentId"
              :data="deptTree"
              :props="defaultProps"
              check-strictly
              default-expand-all
              :placeholder="t('page_sys.dept.placeholderSjbm')"
              value-key="deptId"
              style="width: 260px"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="flex justify-end">
            <el-button
              type="primary"
              v-hasPermi="['system:dept:update']"
              :disabled="!formData.id"
              @click="submitForm"
              >{{ t('action.save') }}</el-button
            >
          </div>
        </template>
      </ContentWrap>
    </div> -->

  <!-- 表单弹窗：添加/修改 -->
  <DeptForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import DeptForm from './DeptForm.vue'
import * as UserApi from '@/api/system/user'
import { CommonStatusEnum } from '@/utils/constants'
import { FormRules } from 'element-plus'
import Sortable from 'sortablejs'

defineOptions({ name: 'SystemDept' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref() // 列表的数据
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: undefined,
  status: undefined,
  orgId: undefined
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

//编辑部门
const formData = ref({
  id: undefined,
  parentId: undefined,
  name: undefined,
  sort: 0,
  status: CommonStatusEnum.ENABLE
})

const formRules = reactive<FormRules>({
  parentId: [{ required: true, message: t('page_sys.dept.tipSjbmBnwk'), trigger: 'blur' }],
  name: [{ required: true, message: t('page_sys.dept.tipBmmcBnwk'), trigger: 'blur' }]
})
const deptTree = ref() // 树形结构
const formLoading = ref(false)

const convertToChinese = (arr) => {
  if (arr) {
    const mapping = {
      '0': '门诊',
      '1': '住院',
      '2': '急诊',
      '3': '全院'
    }
    return arr.map((item) => mapping[item]).join(',')
  } else {
    return ''
  }
}

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeptApi.getDeptList(queryParams)
    list.value = handleTree(data.list)
  } finally {
    loading.value = false
  }
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.orgId = undefined
  queryFormRef.value.resetFields()
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const setEdit = async (row: DeptApi.DeptVO) => {
  getTree()
  try {
    formData.value = await DeptApi.getDept(row.id)
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeptApi.deleteDept(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    getTree()
  } catch {}
}

/** 获得部门树 */
const getTree = async () => {
  deptTree.value = []
  const data = await DeptApi.getSimpleDeptList()
  let dept: Tree = { id: 0, name: t('page_sys.dept.labelDjbm'), children: [] }
  dept.children = handleTree(data)
  deptTree.value.push(dept)
}

const getGroupListTrees = (data: any) => {
  if (Array.isArray(data)) {
    return data.map((item) => getGroupListTrees(item))
  } else if (typeof data === 'object' && data !== null) {
    const result: any = {}
    for (let key in data) {
      if (key === 'name') {
        result.label = data[key]
      } else if (key === 'id') {
        result.value = data[key]
      } else {
        result[key] = getGroupListTrees(data[key])
      }
    }
    return result
  } else {
    return data
  }
}

const orgTree = ref([])
/** 获得机构树 */
const getOrgTree = async () => {
  orgTree.value = []
  const data = await DeptApi.getOrgTree()
  orgTree.value = getGroupListTrees(data.tree)
}

const editFormRef = ref()

const resetEditForm = () => {
  formData.value = {
    id: undefined,
    parentId: undefined,
    name: undefined,
    sort: 0,
    status: CommonStatusEnum.ENABLE
  }
}

const submitForm = async () => {
  // 校验表单
  if (!editFormRef) return
  const valid = await editFormRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeptApi.DeptVO
    await DeptApi.updateDept(data)
    resetEditForm()
    message.success(t('common.updateSuccess'))
    await getList()
    // 发送操作成功的事件
  } finally {
    formLoading.value = false
  }
}

/**
 * 将树数据转化为平铺数据
 * @param <Array> treeData当前要转的id
 * @param <String> childKey 子级字段
 * @return <Array> 返回数据
 */
const treeToTile = (treeData, childKey = 'children') => {
  const arr = []
  const expanded = (data) => {
    if (data && data.length > 0) {
      data
        .filter((d) => d)
        .forEach((e) => {
          arr.push(e)
          expanded(e[childKey] || [])
        })
    }
  }
  expanded(treeData)
  return arr
}

const totileList = ref()

//更新排序
const updateSort = async (upData: DeptApi.DeptVO) => {
  await DeptApi.updateDept(upData)
  message.success(t('common.updateSuccess'))
  await getList()
}

/** 初始化 **/
onMounted(async () => {
  const el = document.querySelector('.tables .el-table__body-wrapper table tbody')
  Sortable.create(el, {
    animation: 150,
    ghostClass: 'blue-background-class',
    // handle: '.drag_btn', // 如果需要点击某个图标拖拽的话需要吧那个图标的class写在这里
    // 写完以上部分就已经可以实现基本的拖拽功能了，以下是拓展
    //始拖拽事件
    onStart: () => {
      totileList.value = treeToTile(list.value)
      // console.log(totileList.value)
    },
    onMove: ({ dragged, related }) => {
      const oldRow = totileList.value[dragged.rowIndex]
      const newRow = totileList.value[related.rowIndex]
      if (oldRow.parentId !== newRow.parentId) {
        return false
      }
    },
    onEnd: (/**Event*/ evt) => {
      let newIndex = evt.newIndex // 排序后的索引位置
      let oldIndex = evt.oldIndex // 排序前的索引位置
      var itemEl = evt.item // 拖拽 HTMLElement
      evt.to // 目标表
      evt.from // 上一个列表
      evt.oldIndex // 元素在旧父级中的旧索引
      evt.newIndex // 元素在新父级中的新索引
      evt.clone // 克隆元件
      evt.pullMode // 当项目在另一个可排序表中时：`“clone”`如果克隆，`true`如果移动
      let newItem = totileList.value[newIndex]
      let oldItem = totileList.value[oldIndex]
      if (oldItem.id !== newItem.id) {
        if (oldItem.sort > newItem.sort) {
          oldItem.sort = newItem.sort - 1
        } else {
          oldItem.sort = newItem.sort + 1
        }
        updateSort(oldItem)
      }
    },
    //点击选中元素事件
    onChoose: (/**Event*/ evt) => {
      evt.oldIndex
    },
    //取消选中事件
    onUnchoose: (/**Event*/ evt) => {}
  })
  try {
    await getList()
  } catch {}

  // 获取用户列表
  userList.value = await UserApi.getSimpleUserList()
  getOrgTree()
})
</script>
